﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Data.Entity;
using System.Text;
using IDAL;
using Model;

namespace DAL
{
    public class SqlshopCarDAL : IshopCarDAL
    {
        GameGOEntities db = DbContextFactory.CreateDbContext();
        public bool isExistGood(int id)
        {
            return db.shopCar.Where(a => a.goodId == id).FirstOrDefault() != null;
        }
        public shopCar GetShopCarByIDAndUid(int id, int uid)
        {
            return db.shopCar.Where(a => a.goodId == id && a.userID == uid).FirstOrDefault();
        }
        public int UpdateNum(int id, int num)
        {
            shopCar sc = db.shopCar.Where(a => a.ID == id).FirstOrDefault();
            sc.goodNum = num;
            sc.sumPrice = num * sc.goodPrice;
            db.Set<shopCar>().Attach(sc);
            db.Entry<shopCar>(sc).State = EntityState.Modified;
            db.SaveChanges();
            return num;
        }
        public void AddShoppingCar(int goodID, int uid, int num)
        {
            goods good = db.goods.Where(a => a.ID == goodID).FirstOrDefault();
            shopCar car = new shopCar()
            {
                userID = uid,
                goodId = goodID,
                goodNum = num,
                goodPrice = good.goodprice,
                sumPrice = good.goodprice * num
            };
            db.shopCar.Add(car);
            db.SaveChanges();
        }
        public IQueryable<shopCar> GetShopCarByUid(int uid)
        {
            return db.shopCar.Where(a => a.userID == uid);
        }
        public void DeleteSingleShoppingCar(int id)
        {
            db.shopCar.Remove(db.shopCar.Where(a => a.ID == id).FirstOrDefault());
            db.SaveChanges();
        }
        public shopCar GetShopCarByID(int id)
        {
            return db.shopCar.Where(a => a.ID == id).FirstOrDefault();
        }
    }
}